package net.valerijtimakov.homefinances.dao.storages.user.mysql;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import net.valerijtimakov.homefinances.domain.common.DataItem;
import net.valerijtimakov.homefinances.domain.user.UserItem;
import net.valerijtimakov.homefinances.exceptions.AppExceptionWrongState;
import net.valerijtimakov.homefinances.exceptions.AppPersProviderException;
import net.valerijtimakov.homefinances.exceptions.AppPersistentException;
import net.valerijtimakov.homefinances.exceptions.wrongarg.AppExceptionNullArgument;
import net.valerijtimakov.homefinances.dao.storages.common.mysql.ItemsStorage;
import net.valerijtimakov.homefinances.dao.storages.finances.mysql.IMySqlProvider;
import net.valerijtimakov.homefinances.dao.storages.user.IUserStorage;

public class UserStorage extends ItemsStorage implements IUserStorage {
	
	private String nameFieldName = "name";
	private String loginFieldName = "login";
	private String emailFieldName = "email";
	
	public UserStorage(IMySqlProvider provider) throws AppExceptionWrongState {
		super(provider);
	}

	public Map<Long, UserItem> getUsers(long... id) 
		throws AppPersProviderException, AppExceptionWrongState 
	{
		return getItemsByIds(id);
	}

	public void addUser(UserItem user) throws AppPersistentException, 
		AppExceptionNullArgument, AppExceptionWrongState 
	{
		addItem(user, "Не задан экземпляр пользователя!", "Ошибка добавления пользователя!");
	}

	public void removeUser(long id) throws AppPersProviderException, AppExceptionWrongState {
		delete(id);
	}

	public void updateUser(UserItem user) throws AppPersProviderException, AppExceptionWrongState {
		update(user);
	}

	@Override
	protected DataItem createTempItem() {
		return new UserItem();
	}
	
	@Override
	protected String getTableName() {
		return "user";
	}

	@Override
	protected <T extends DataItem> void parse(ResultSet rs, T item) throws SQLException {
		super.parse(rs, item);
		UserItem cItem = (UserItem)item;
		cItem.setName(rs.getString(nameFieldName));
		cItem.setLogin(rs.getString(loginFieldName));
		cItem.setEmail(rs.getString(emailFieldName));
	}
	
	@Override
	protected void initSelect() {
		super.initSelect();
		selectQuery.addField(nameFieldName);
		selectQuery.addField(loginFieldName);
		selectQuery.addField(emailFieldName);
	}

	@Override
	protected <T extends DataItem> void addData(T item) {
		UserItem cItem = (UserItem)item;
		insertQuery.setFieldValue(nameFieldName, cItem.getName());
		insertQuery.setFieldValue(loginFieldName, cItem.getLogin());
		insertQuery.setFieldValue(emailFieldName, cItem.getEmail());
	}

	@Override
	protected <T extends DataItem> void setUpdatedFields(T item) {
		UserItem cItem = (UserItem)item;
		updateQuery.setFieldValue(nameFieldName, cItem.getName());
		updateQuery.setFieldValue(loginFieldName, cItem.getLogin());
		updateQuery.setFieldValue(emailFieldName, cItem.getEmail());
	}
}
